package cn.xgxd.web;


import cn.xgxd.config.JWTUtils;
import cn.xgxd.result.Result;
import cn.xgxd.pojo.User;
import cn.xgxd.service.UserService;
import cn.xgxd.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserContext userContext;
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User u = userService.search(user);
        if (u!=null){
            Map<String, Object> claims = new HashMap<>();
            Map<String, Object> token = new HashMap<>();
            claims.put("id",u.getId());
            String jwt = JWTUtils.generateJwt(claims);
            token.put("token",jwt);
            token.put("admin",u.getAdmin());
            return Result.success(token);
        }else {
            return Result.error("用户名或账号错误");
        }
    }

    @GetMapping("/{id}")
    public Result findUserById(@PathVariable ("id") Integer id){
        User search = userService.search(id);
        return search!=null?Result.success(search):Result.error("没找到用户");
    }

    @GetMapping("/total")
    public Result userTotal(){
        return Result.success(userService.userTotal());
    }



    @PostMapping("/register")
    public Result register(@RequestBody User user){
        System.out.println(user);
        boolean register = userService.register(user);
        return register?Result.success():Result.error("用户名或号码已经存在了");
    }
    @PostMapping
    public Result getUserById(){
        return Result.success(userService.getUserById(userContext.getUserId()));
    }

    @PutMapping("/updata")
    public Result upData(@RequestBody User user){
        userService.upData(user);
        return Result.success();
    }
    @GetMapping("/admin")
    public Result getAdmin(){
        return Result.success(userService.getAdmin());
    }

    @GetMapping("/normal")
    public Result getUser(){
        return Result.success(userService.getUser());
    }

    @PutMapping("/swadmin")
    public Result swAdmin(@RequestBody User user){
        userService.swAdmin(user);
        return Result.success();
    }
}
